package com.xiaotao;

import org.postgresql.PGConnection;
import org.postgresql.PGNotification;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * Hello world!
 *
 * @author xiaotao
 */
public class App 
{
    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection(
                "jdbc:postgresql://10.10.10.114:5432/postgres", "postgres", "admin_postgres")) {

            PGConnection pgConnection = connection.unwrap(PGConnection.class);

            // Start listening to the channel
            try (Statement statement = connection.createStatement()) {
                statement.execute("LISTEN table_changes");
            }

            System.out.println("Listening for notifications on channel 'my_channel'...");

            while (true) {
                PGNotification[] notifications = pgConnection.getNotifications();
                if (notifications != null) {
                    for (PGNotification notification : notifications) {
                        System.out.println("Received notification: " + notification.getParameter());
                    }
                }

                // Sleep for a short while to avoid busy-waiting
                Thread.sleep(500);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
